package com.cn.coder;

import com.cn.common.RemoteCommand;
import com.cn.msg.Message;
import com.cn.util.UtilAll;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.ByteBuffer;

/**
 * 消息编码器
 */
public class MessageEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ct, Message msg, ByteBuf out) throws Exception {
        if (null == msg) {
            return;
        }
        try {
            out.writeBytes(UtilAll.encodeHeader(msg));
            if (msg.getByteBodys() != null && msg.getByteBodys().length > 0) {
                out.writeInt(msg.getByteBodys().length);
                out.writeBytes(msg.getByteBodys());
            }
        } catch (Exception e) {
            System.out.println("编码异常：" + this.getClass().getSimpleName());
//            e.printStackTrace();
            ct.close();
        }

    }

}
